<template>
  <div ref="chartRef" style="width: 100vw; height: 400px;"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch ,defineProps} from 'vue';
import * as echarts from 'echarts';
import { getWant } from "@/api/index";

const data = ref([]);  // 用来存储图表数据
const chartRef = ref<HTMLElement | null>(null);

// const { type } = defineProps(['want'])
// data.value = type.map(item => ({
//   value: item.yValue,
//   name: item.xValue
// }));

// 获取数据
getWant().then(res => {
  // console.log(res.data.data.userProfile.occupationInfoChart.series[0].points);
  const result = res.data.data.userProfile.userMovieInterestInfoChart.series[0].points;
  // 映射数据，确保数据结构正确
  data.value = result.map(item => ({
    value: item.yValue,
    name: item.xValue
  }));
  // console.log(data.value);

});
// 初始化配置项
const option = ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '5%',
    left: 'center'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: data.value
    }
  ]
});

// 更新图表函数
function updateChart() {
  if (chartRef.value !== null) {
    const myChart = echarts.getInstanceByDom(chartRef.value);
    if (myChart) {
      myChart.dispose();  // 销毁已有实例
    }

    const newChart = echarts.init(chartRef.value);  // 创建新实例
    newChart.setOption(option.value);  // 更新图表配置
  }
}

// 监视 data 的变化，并在数据更新后重新渲染图表
watch(data, () => {
  if (data.value.length) {
    option.value = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      series: [
        {
          name: 'Access From',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 40,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data.value
        }
      ]
    };

    // 数据更新后重绘图表
    updateChart();
  }
}, { immediate: true });

onMounted(() => {
  // 初始图表渲染
  if (chartRef.value !== null) {
    const myChart = echarts.init(chartRef.value);
    myChart.setOption(option.value);
  }
});
</script>

<style scoped></style>